package reflectObject;

import java.io.IOException;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.Translator;
import javassist.expr.ExprEditor;
import javassist.expr.Handler;

/**
 * Translateur d'objet reflect
 * Injecte des instructions de trap d'exception, de store et restaure d'objets transactionnable.
 * @author 3003064 & 3153319
 *
 */
public class MakePublicTranslator implements Translator{

	@Override
	public void onLoad(ClassPool pool, String classname) throws NotFoundException, CannotCompileException {	
		if(classname.contains("junit")) return ;
		CtClass myCtClass = pool.get(classname);

		for(CtMethod myCtMethod : myCtClass.getDeclaredMethods()){
			if(myCtMethod.getName().startsWith("set")){
				String before = "{ StoreEnvirThread.AddObjectInTheLastEnv(this);}";
				myCtMethod.insertBefore(before);
				try {
					myCtClass.writeFile();
					myCtClass.defrost();
				} catch (IOException e1) {
					System.out.println(" Probleme de sauvegarede des injection de code ");
				}
			} else {
				if(myCtMethod.hasAnnotation(fr.upmc.aladyn.transactionables.annotation.Transactionnable.class)){
					
					String before = "{  StoreEnvirThread.newEnv(); " +
										"   StoreEnvirThread.AddObjectInTheLastEnv(this);}"; 
					String after  = "{  StoreEnvirThread.DeleteLastEnv();}";
					String inCatch = "{ System.out.println(\"**************>          Il Existe une erreur , Restauration des objets*************\"); StoreEnvirThread.RestaureAndRemoveLastEnv(); return;}";
					myCtMethod.addCatch(inCatch, pool.get("java.lang.Throwable"));
					myCtMethod.insertBefore(before);
					myCtMethod.insertAfter(after);
				}
			}

			myCtMethod.instrument(new ExprEditor(){
				public void edit(Handler h){
					try {
						h.insertBefore("{StoreEnvirThread.RestaureAndRemoveLastEnv(); return;}");
					} catch (CannotCompileException e) {
						System.out.println(" Probleme de sauvegarede des injection de code ");
					}
				}
			});
		}

	}

	@Override
	public void start(ClassPool pool) throws NotFoundException,CannotCompileException {}

}
